package com.tjp.eight.ui.fragment.tabvideo;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.baoyz.widget.PullRefreshLayout;
import com.google.gson.Gson;
import com.tjp.eight.R;
import com.tjp.eight.ResultModel;
import com.tjp.eight.constant.ConstantUtils;
import com.tjp.eight.ui.fragment.BaseFragment;
import com.tjp.eight.ui.fragment.detail.ShareModel;
import com.tjp.eight.ui.fragment.detail.SharePostModel;
import com.tjp.eight.utils.ActivityUtils;
import com.tjp.eight.utils.Cutils;
import com.tjp.eight.utils.DescriptUtils;
import com.tjp.eight.utils.IsSuccessUtils;
import com.tjp.eight.utils.SharePreferencesUtils;
import com.tjp.eight.utils.ToatUtils;
import com.tjp.eight.views.LogoutDailog;
import com.tjp.eight.views.ShareDialog;
import com.tjp.eight.views.rcview.EndlessRecyclerOnScrollListener;
import com.tjp.eight.views.rcview.HeaderViewRecyclerAdapter;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;


/**
 * Created by Administrator on 2017/2/13.
 */

public class FragmentVideo extends BaseFragment<VideoPresenter> implements FVideoView {
    private VideoAdapter videoAdapter;
    private TextView tv_title;
    private RecyclerView rv_video;
    private HeaderViewRecyclerAdapter headerViewRecyclerAdapter;
    private EndlessRecyclerOnScrollListener endlessRecyclerOnScrollListener;
    private int page = 1;
    private boolean isRefresh = true;
    private View footView;
    private PullRefreshLayout refreshLayout;
    private LinearLayoutManager linearLayoutManager;
    private int currentViewsPos = 0;
    private int currentZanPos = 0;
    private ShareDialog shareDialog;
    private int currentShareType = -1;
    private String comeFrom = "来自八秒视频";
    private String cvid = "";
    private LogoutDailog dialogLogin;
    private int position = -1;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = super.onCreateView(inflater, container, savedInstanceState);

        if (contentView == null) {
            contentView = inflater.inflate(R.layout.frag_video_layout, container, false);
        }

        initViews();
        return contentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        page = 1;
        isRefresh = true;
        presenter.loadData(getPostJson());
    }

    @Override
    protected VideoPresenter createPresenter() {
        return new VideoPresenter(this);
    }


    @Override
    public void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            JCVideoPlayer.releaseAllVideos();
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void showToast(String msg) {

    }

    @Override
    public void addData(VideoModel model) {

    }

    @Override
    public void loadFail(String msg) {
        refreshLayout.setRefreshing(false);
        //ToatUtils.toastCommentFail(getContext(), msg);
    }

    @Override
    public void loadData(VideoResultModel model) {
        refreshLayout.setRefreshing(false);
        isRefresh = false;
        endlessRecyclerOnScrollListener.reSet();
        if (model == null || model.data == null) return;
        if (model.data != null)
            videoAdapter.rdata(model.data.list);
        if (IsSuccessUtils.isSuccess(model.result)) {
            if (model.data.total_items == videoAdapter.getItemCount()) {
                headerViewRecyclerAdapter.removeFootByIndex(0);
            } else {
                if (headerViewRecyclerAdapter.getFooterCount() == 0) {
                    headerViewRecyclerAdapter.addFooterView(footView);
                }
            }
        } else {
            ToatUtils.toastCommentFail(getContext(), model.result);
        }
    }

    @Override
    public void updateZan(ResultModel model) {
        if (model == null) return;
        if (IsSuccessUtils.isSuccess(model.result)) {
            videoAdapter.setZanTvCount(0, currentZanPos);
        } else {
            ToatUtils.toastCommentFail(getContext(), model.msg);
        }
    }

    @Override
    public void updateViews(ResultModel model) {
        if (model == null) return;
        if (IsSuccessUtils.isSuccess(model.result)) {
            videoAdapter.setViewsCount(0, currentViewsPos);
        } else {
            ToatUtils.toastCommentFail(getContext(), model.msg);
        }
    }

    @Override
    public void shareSuccess(ShareModel model) {
        dismissShare();
        if (model == null || model.data == null) return;
        if (IsSuccessUtils.isSuccess(model.result)) {
            // AppUtils.check(getActivity());
            UMImage thumb = new UMImage(getActivity(), model.data.cover_path);
            UMWeb web = new UMWeb(model.data.url);
            web.setTitle(model.data.title);
            web.setDescription(model.data.des);
            web.setThumb(thumb);

            switch (currentShareType) {
                case ShareDialog.TYPE_WX:
                    new ShareAction(getActivity()).setPlatform(SHARE_MEDIA.WEIXIN).withText(comeFrom).withMedia(web)
                            .setCallback(umShareListener).share();
                    break;
                case ShareDialog.TYPE_WX_CIRCLE:
                    new ShareAction(getActivity()).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).withText(comeFrom).setCallback(umShareListener).withMedia(web).share();
                    break;
                case ShareDialog.TYPE_QQ:
                    new ShareAction(getActivity()).setPlatform(SHARE_MEDIA.QQ).withText(comeFrom).withMedia(web).setCallback(umShareListener).share();
                    break;
                case ShareDialog.TYPE_QQ_ZONE:
                    new ShareAction(getActivity()).setPlatform(SHARE_MEDIA.QZONE).withText(comeFrom).withMedia(web).setCallback(umShareListener).share();
                    break;
                case ShareDialog.TYPE_COLLECTION:
                    // presenter.collcetion(getCPJson(caid));
                    break;
                case ShareDialog.TYPE_REPORT:
                    //TODO

                    break;
                case ShareDialog.TYPE_DISMISS:
                    dismissShare();
                    break;
            }
        } else {
            ToatUtils.toastSuccess(getContext(), model.msg);
        }
    }

    @Override
    public void loadMData(VideoResultModel model) {
        refreshLayout.setRefreshing(false);
        isRefresh = false;
        if (model == null || model.data == null) return;
        if (model.data != null)
            videoAdapter.addData(model.data.list);
        if (IsSuccessUtils.isSuccess(model.result)) {
            if (model.data.total_items == videoAdapter.getItemCount()) {
                headerViewRecyclerAdapter.removeFootByIndex(0);
            } else {
                if (headerViewRecyclerAdapter.getFooterCount() == 0) {
                    headerViewRecyclerAdapter.addFooterView(footView);
                }
            }
        } else {
            ToatUtils.toastCommentFail(getContext(), model.result);
        }
    }

    @Override
    public void reLoadUrl(VideoReLoadUrlResultModel model) {
        if (model != null) {
            if (IsSuccessUtils.isSuccess(model.result)) {
                videoAdapter.mUrl(position, model.url);
            }
        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA share_media) {
            ToatUtils.toastSuccess(getContext(), "分享成功");
            presenter.shareSuccess(getShareRJson());
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            if (throwable != null)
                ToatUtils.toastSuccess(getContext(), "分享失败！由" + throwable.getMessage() + "导致");
            else
                ToatUtils.toastSuccess(getContext(), "分享失败！");
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            ToatUtils.toastSuccess(getContext(), "用户取消分享");
        }
    };

    private void initViews() {
        tv_title = (TextView) contentView.findViewById(R.id.tv_title);
        tv_title.setText("视频");

        rv_video = (RecyclerView) contentView.findViewById(R.id.rv_video);
        linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        rv_video.setLayoutManager(linearLayoutManager);

        videoAdapter = new VideoAdapter(getActivity());
        videoAdapter.setShareVideo(new VideoAdapter.ShareVideo() {
            @Override
            public void share(String vid) {
                showShare(vid);
            }
        });
        videoAdapter.setGetOUrl(new VideoAdapter.GetOUrl() {
            @Override
            public void getOUrl(int pos, String vid) {
                //videoAdapter.mUrl(pos,"http://2449.vod.myqcloud.com/2449_22ca37a6ea9011e5acaaf51d105342e3.f20.mp4");
                position = pos;
                presenter.reLoadUrl(vid);
            }
        });
        headerViewRecyclerAdapter = new HeaderViewRecyclerAdapter(videoAdapter);
        footView = LayoutInflater.from(getContext()).inflate(R.layout.swipe_refresh_footer, rv_video, false);
        headerViewRecyclerAdapter.addFooterView(footView);
        endlessRecyclerOnScrollListener = new EndlessRecyclerOnScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                //  JCVideoPlayer.releaseAllVideos();
                if (!isRefresh) {
                    page = currentPage;
                    presenter.loadMData(getPostJson());
                } else {
                    endlessRecyclerOnScrollListener.reSet();
                }
            }
        };
        rv_video.addOnScrollListener(endlessRecyclerOnScrollListener);
        rv_video.setAdapter(headerViewRecyclerAdapter);
        refreshLayout = (PullRefreshLayout) contentView.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                JCVideoPlayer.releaseAllVideos();
                endlessRecyclerOnScrollListener.reSet();
                page = 1;
                isRefresh = true;
                presenter.loadData(getPostJson());
            }
        });
        videoAdapter.setUpdateCount(new VideoAdapter.UpdateCount() {
            @Override
            public void update(int pos, int type, String vid) {
                //更新views
                currentViewsPos = pos;
                presenter.updateViewCount(getPostUJson(vid, "count"));
            }
        });
        videoAdapter.setUpdateZanCount(new VideoAdapter.UpdateZanCount() {
            @Override
            public void update(int pos, int type, String vid) {
                if (!SharePreferencesUtils.isLogin()) {
                    showIsLogin();
                    return;
                }
                //更新赞数
                currentZanPos = pos;
                presenter.updateZanCount(getPostUJsonZ(vid, "praise"));
            }
        });

    }

    void showIsLogin() {
        if (dialogLogin == null) {
            dialogLogin = new LogoutDailog(getActivity());
        }
        dialogLogin.setTextTitle("亲！你还没登录呢");
        dialogLogin.setLogoutInterface(new LogoutDailog.LogoutInterface() {
            @Override
            public void logout() {
                ActivityUtils.startLoginForResult(getActivity());
                dialogLogin.dismiss();
            }
        });
        dialogLogin.setCancelText("再去逛逛");
        dialogLogin.setOkText("去登录");
        dialogLogin.show();
    }

    private String getPostJson() {
        VideoPostModel model = new VideoPostModel();
        model.page = page;
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    private String getPostUJson(String vid, String act) {
        VideoPModel model = new VideoPModel();
        model.vid = vid;
        model.act = act;
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    private String getPostUJsonZ(String vid, String act) {
        VideoPModel model = new VideoPModel();
        model.vid = vid;
        model.act = act;
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    void showShare(final String vid) {
        if (shareDialog == null) {
            shareDialog = new ShareDialog(getContext());
        }
        shareDialog.setOnClickType(new ShareDialog.OnClickType() {
            @Override
            public void clickType(int type) {
                currentShareType = type;
                presenter.getShareData(getShareJson(vid));
                switch (type) {
                    case ShareDialog.TYPE_WX:
                        break;
                    case ShareDialog.TYPE_WX_CIRCLE:
                        break;
                    case ShareDialog.TYPE_QQ:
                        break;
                    case ShareDialog.TYPE_QQ_ZONE:
                        break;
                    case ShareDialog.TYPE_COLLECTION:
                        break;
                    case ShareDialog.TYPE_REPORT:
                        break;
                    case ShareDialog.TYPE_DISMISS:
                        dismissShare();
                        break;
                }
            }
        });
        shareDialog.setRCVisible(View.INVISIBLE);
        shareDialog.show();
    }

    private String getShareJson(String vid) {
        SharePostModel model = new SharePostModel();
        model.vid = vid;
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    private String getShareRJson() {
        SharePostModel model = new SharePostModel();
        model.cid = cvid;
        model.type = "2";
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        model.authcode = Cutils.getInstance().getCode();
        model.time = System.currentTimeMillis() / 1000 + "";
        model.md5authcode = DescriptUtils.SHA1(model.time + model.authcode + model.authcode + ConstantUtils.SHA1);
        return new Gson().toJson(model);
    }

    void dismissShare() {
        if (shareDialog != null) {
            shareDialog.dismiss();
        }
    }

    public void scrollTop() {
        if (rv_video != null) {
            rv_video.scrollToPosition(0);
        }
    }
}
